package com.atguigu.chapter07.D04_State;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.util.Collector;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.util.Properties;

import static org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION;
import static org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer.Semantic.EXACTLY_ONCE;

/**
 * Author: Pepsi
 * Date: 2023/8/12
 * Desc:
 */
public class Flink11_Kafka_Flink_Kafka {
    public static void main(String[] args) {

        System.setProperty("HADOOP_USER_NAME","atguigu");

        Configuration conf = new Configuration();
        conf.setInteger("rest.port",1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        // 开启checkpoint
        env.enableCheckpointing(2000);
        env.setStateBackend(new HashMapStateBackend());
        // 设置额checkpoint目录
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop101:8020/flink-checkpoint_5");

        // 设置checkpoint的严格一次
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);

        // 限制同时进行checkpoint的数量的上限
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
        // 两个checkpoint之间最小的时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
        // 1.13.6 新增的方法：当程序取消的时候保留hdfs中的checkpoint数据
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(RETAIN_ON_CANCELLATION);




        Properties sourceProps = new Properties();
        sourceProps.put("bootstrap.servers","hadoop101:9092,hadoop102:9092,hadoop103:9092");
        sourceProps.put("group.id","flink_consumer_group");
        // 防止重复读取那些未提交的数据
        sourceProps.put("isolation.level","read_committed"); //消费开启事务的topic的时候，只消费已经提交的

        Properties sinkConfig = new Properties();
        sinkConfig.put("bootstrap.servers","hadoop101:9092,hadoop102:9092,hadoop103:9092");
        sinkConfig.put("transaction.timeout.ms",15*60*1000);

        SingleOutputStreamOperator<Tuple2<String, Long>> stream = env
                .addSource(
                        new FlinkKafkaConsumer<String>("flink_source_kafka", new SimpleStringSchema(), sourceProps)
                                .setStartFromLatest()
                )
                .flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                        for (String word : value.split(" ")) {
                            out.collect(Tuple2.of(word, 1L));
                        }
                    }
                })
                .keyBy(s -> s.f0)
                .sum(1);
        stream
                .addSink(new FlinkKafkaProducer<Tuple2<String, Long>>(
                        "default",
                        new KafkaSerializationSchema<Tuple2<String, Long>>() {
                            @Override
                            public ProducerRecord<byte[], byte[]> serialize(Tuple2<String, Long> element, @Nullable Long timestamp) {
                                return new ProducerRecord<>("flink_sink_kafka",(element.f0+"_"+element.f1).getBytes());
                            }
                        },
                        sinkConfig,
                        EXACTLY_ONCE
                ));
        stream
                .addSink(new SinkFunction<Tuple2<String, Long>>() {
                    @Override
                    public void invoke(Tuple2<String, Long> value,
                                       Context context) throws Exception {
                        if (value.f0.contains("x")){
                            throw new RuntimeException("手动抛出异常...");
                        }
                    }
                });


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
